package ui;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import java.awt.*;
import dao.ContactDAO;
import dao.FileContactDAO;
import model.Contact;
import model.FriendContact;
import model.WorkContact;
import exception.ContactException;

public class MainFrame extends JFrame {
    private ContactDAO contactDAO;
    private JTable contactTable;
    private DefaultTableModel tableModel;
    private static final Color PRIMARY_COLOR = new Color(51, 122, 183);
    private static final Color BACKGROUND_COLOR = new Color(245, 245, 245);
    private static final String ADMIN_USERNAME = "admin";
    private static final String ADMIN_PASSWORD = "123456";

    public MainFrame() {
        if (!showLoginDialog()) {
            System.exit(0);  // 如果登录失败，直接退出程序
        }
        
        try {
            UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (Exception e) {
            e.printStackTrace();
        }
        contactDAO = new FileContactDAO();
        initUI();
    }

    private boolean showLoginDialog() {
        JDialog loginDialog = new JDialog((Frame) null, "管理员登录", true);
        loginDialog.setLayout(new BorderLayout());
        loginDialog.setSize(350, 250);
        loginDialog.setLocationRelativeTo(null);
        
        // 创建主面板，使用 MigLayout 提供更灵活的布局
        JPanel mainPanel = new JPanel(new BorderLayout(0, 15));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 25, 20, 25));
        mainPanel.setBackground(Color.WHITE);

        // 创建标题面板
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        titlePanel.setBackground(Color.WHITE);
        JLabel titleLabel = new JLabel("通讯录管理系统");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 20));
        titleLabel.setForeground(PRIMARY_COLOR);
        titlePanel.add(titleLabel);

        // 创建表单面板
        JPanel formPanel = new JPanel(new GridLayout(2, 1, 0, 15));
        formPanel.setBackground(Color.WHITE);

        // 创建用户名面板
        JPanel usernamePanel = new JPanel(new BorderLayout(5, 0));
        usernamePanel.setBackground(Color.WHITE);
        JTextField usernameField = new JTextField();
        usernameField.setPreferredSize(new Dimension(200, 30));
        JLabel userIcon = new JLabel("👤");  // 使用 Unicode 字符作为图标
        userIcon.setFont(new Font("Dialog", Font.PLAIN, 20));
        usernamePanel.add(userIcon, BorderLayout.WEST);
        usernamePanel.add(usernameField, BorderLayout.CENTER);

        // 创建密码面板
        JPanel passwordPanel = new JPanel(new BorderLayout(5, 0));
        passwordPanel.setBackground(Color.WHITE);
        JPasswordField passwordField = new JPasswordField();
        passwordField.setPreferredSize(new Dimension(200, 30));
        JLabel passIcon = new JLabel("🔒");  // 使用 Unicode 字符作为图标
        passIcon.setFont(new Font("Dialog", Font.PLAIN, 20));
        passwordPanel.add(passIcon, BorderLayout.WEST);
        passwordPanel.add(passwordField, BorderLayout.CENTER);

        formPanel.add(usernamePanel);
        formPanel.add(passwordPanel);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));
        buttonPanel.setBackground(Color.WHITE);

        final boolean[] loginSuccess = {false};

        // 美化登录按钮
        JButton loginButton = new JButton("登录");
        loginButton.setPreferredSize(new Dimension(100, 35));
        loginButton.setBackground(PRIMARY_COLOR);
        loginButton.setForeground(Color.WHITE);
        loginButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        loginButton.setBorderPainted(false);
        loginButton.setFocusPainted(false);
        loginButton.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 美化取消按钮
        JButton cancelButton = new JButton("取消");
        cancelButton.setPreferredSize(new Dimension(100, 35));
        cancelButton.setBackground(Color.LIGHT_GRAY);
        cancelButton.setForeground(Color.WHITE);
        cancelButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        cancelButton.setBorderPainted(false);
        cancelButton.setFocusPainted(false);
        cancelButton.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 添加按钮悬停效果
        loginButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                loginButton.setBackground(PRIMARY_COLOR.darker());
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                loginButton.setBackground(PRIMARY_COLOR);
            }
        });

        cancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                cancelButton.setBackground(Color.GRAY);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                cancelButton.setBackground(Color.LIGHT_GRAY);
            }
        });

        // 添加登录逻辑
        loginButton.addActionListener(e -> {
            String username = usernameField.getText();
            String password = new String(passwordField.getPassword());
            
            if (ADMIN_USERNAME.equals(username) && ADMIN_PASSWORD.equals(password)) {
                loginSuccess[0] = true;
                loginDialog.dispose();
            } else {
                JOptionPane.showMessageDialog(loginDialog,
                    "用户名或密码错误！",
                    "登录失败",
                    JOptionPane.ERROR_MESSAGE);
                passwordField.setText("");
                usernameField.requestFocus();
            }
        });

        cancelButton.addActionListener(e -> {
            loginSuccess[0] = false;
            loginDialog.dispose();
        });

        buttonPanel.add(loginButton);
        buttonPanel.add(cancelButton);

        // 组装主面板
        mainPanel.add(titlePanel, BorderLayout.NORTH);
        mainPanel.add(formPanel, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        // 添加主面板到对话框
        loginDialog.add(mainPanel);

        // 设置回车键触发登录
        loginDialog.getRootPane().setDefaultButton(loginButton);

        // 显示对话框
        loginDialog.setVisible(true);

        return loginSuccess[0];
    }

    private void initUI() {
        setTitle("通讯录管理系统");
        setSize(900, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);  // 居中显示

        // 设置整体背景色
        getContentPane().setBackground(BACKGROUND_COLOR);

        // 创建顶部面板
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBackground(PRIMARY_COLOR);
        topPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建标题标签
        JLabel titleLabel = new JLabel("通讯录管理系统", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titleLabel.setForeground(Color.WHITE);
        topPanel.add(titleLabel, BorderLayout.CENTER);

        // 创建工具栏
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 5));
        buttonPanel.setOpaque(false);

        JButton addButton = createStyledButton("添加联系人", "/icons/add.png");
        JButton editButton = createStyledButton("编辑联系人", "/icons/edit.png");
        JButton deleteButton = createStyledButton("删除联系人", "/icons/delete.png");

        buttonPanel.add(addButton);
        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);

        // 创建表格
        String[] columns = {"类型", "姓名", "电话", "邮箱", "其他信息"};
        tableModel = new DefaultTableModel(columns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;  // 设置表格不可编辑
            }
        };

        contactTable = new JTable(tableModel);
        styleTable(contactTable);

        // 创建主面板，使用BorderLayout布局
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBackground(BACKGROUND_COLOR);
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 添加组件到主面板
        mainPanel.add(buttonPanel, BorderLayout.NORTH);
        mainPanel.add(new JScrollPane(contactTable), BorderLayout.CENTER);

        // 添加到框架
        add(topPanel, BorderLayout.NORTH);
        add(mainPanel, BorderLayout.CENTER);

        // 添加事件监听
        addButton.addActionListener(e -> showAddDialog());
        editButton.addActionListener(e -> showEditDialog());
        deleteButton.addActionListener(e -> deleteContact());

        refreshTable();
    }

    private JButton createStyledButton(String text, String iconPath) {
        JButton button = new JButton(text);
        try {
            ImageIcon icon = new ImageIcon(getClass().getResource(iconPath));
            Image img = icon.getImage().getScaledInstance(20, 20, Image.SCALE_SMOOTH);
            button.setIcon(new ImageIcon(img));
        } catch (Exception e) {
            // 如果图标加载失败，继续使用纯文本按钮
        }
        button.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        button.setForeground(Color.WHITE);
        button.setBackground(PRIMARY_COLOR);
        button.setBorderPainted(false);
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));
        button.setPreferredSize(new Dimension(150, 40));

        // 添加鼠标悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(PRIMARY_COLOR.darker());
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(PRIMARY_COLOR);
            }
        });

        return button;
    }

    private void styleTable(JTable table) {
        // 设置表格样式
        table.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        table.setRowHeight(30);
        table.setIntercellSpacing(new Dimension(10, 5));
        table.setGridColor(new Color(230, 230, 230));
        table.setShowVerticalLines(true);
        table.setShowHorizontalLines(true);

        // 设置表头样式
        JTableHeader header = table.getTableHeader();
        header.setFont(new Font("微软雅黑", Font.BOLD, 14));
        header.setBackground(PRIMARY_COLOR);
        header.setForeground(Color.WHITE);
        header.setPreferredSize(new Dimension(header.getWidth(), 40));

        // 设置选择行的颜色
        table.setSelectionBackground(new Color(232, 242, 254));
        table.setSelectionForeground(Color.BLACK);
    }

    private void refreshTable() {
        tableModel.setRowCount(0);
        for (Contact contact : contactDAO.getAllContacts()) {
            Object[] row = new Object[5];
            row[0] = contact.getType();
            row[1] = contact.getName();
            row[2] = contact.getPhone();
            row[3] = contact.getEmail();
            if (contact instanceof FriendContact) {
                row[4] = ((FriendContact) contact).getBirthday();
            } else if (contact instanceof WorkContact) {
                row[4] = ((WorkContact) contact).getCompany();
            }
            tableModel.addRow(row);
        }
    }

    private void showAddDialog() {
        // 实现添加联系人的对话框
        JDialog dialog = new JDialog(this, "添加联系人", true);
        dialog.setLayout(new BorderLayout());
        dialog.setSize(400, 300);

        JPanel panel = new JPanel(new GridLayout(6, 2, 5, 5));
        JComboBox<String> typeCombo = new JComboBox<>(new String[]{"朋友", "工作"});
        JTextField nameField = new JTextField();
        JTextField phoneField = new JTextField();
        JTextField emailField = new JTextField();
        JTextField extraField = new JTextField();

        panel.add(new JLabel("类型:"));
        panel.add(typeCombo);
        panel.add(new JLabel("姓名:"));
        panel.add(nameField);
        panel.add(new JLabel("电话:"));
        panel.add(phoneField);
        panel.add(new JLabel("邮箱:"));
        panel.add(emailField);
        panel.add(new JLabel("其他信息:"));
        panel.add(extraField);

        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(e -> {
            try {
                Contact contact;
                if (typeCombo.getSelectedItem().equals("朋友")) {
                    contact = new FriendContact(
                        nameField.getText(),
                        phoneField.getText(),
                        emailField.getText(),
                        extraField.getText()
                    );
                } else {
                    contact = new WorkContact(
                        nameField.getText(),
                        phoneField.getText(),
                        emailField.getText(),
                        extraField.getText()
                    );
                }
                contactDAO.addContact(contact);
                refreshTable();
                dialog.dispose();
            } catch (ContactException ex) {
                JOptionPane.showMessageDialog(dialog, ex.getMessage());
            }
        });

        panel.add(saveButton);
        dialog.add(panel, BorderLayout.CENTER);
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }

    private void showEditDialog() {
        int selectedRow = contactTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要编辑的联系人");
            return;
        }

        String name = (String) tableModel.getValueAt(selectedRow, 1);
        Contact contact = contactDAO.findContact(name);
        if (contact == null) return;

        // 创建编辑对话框
        JDialog dialog = new JDialog(this, "编辑联系人", true);
        dialog.setLayout(new BorderLayout());
        dialog.setSize(400, 300);

        JPanel panel = new JPanel(new GridLayout(6, 2, 5, 5));
        
        // 创建表单组件
        JComboBox<String> typeCombo = new JComboBox<>(new String[]{"朋友", "工作"});
        JTextField nameField = new JTextField(contact.getName());
        JTextField phoneField = new JTextField(contact.getPhone());
        JTextField emailField = new JTextField(contact.getEmail());
        JTextField extraField = new JTextField();

        // 设置当前联系人类型和额外信息
        if (contact instanceof FriendContact) {
            typeCombo.setSelectedItem("朋友");
            extraField.setText(((FriendContact) contact).getBirthday());
        } else if (contact instanceof WorkContact) {
            typeCombo.setSelectedItem("工作");
            extraField.setText(((WorkContact) contact).getCompany());
        }

        // 添加组件到面板
        panel.add(new JLabel("类型:"));
        panel.add(typeCombo);
        panel.add(new JLabel("姓名:"));
        panel.add(nameField);
        panel.add(new JLabel("电话:"));
        panel.add(phoneField);
        panel.add(new JLabel("邮箱:"));
        panel.add(emailField);
        panel.add(new JLabel("其他信息:"));
        panel.add(extraField);

        // 创建���钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 5));

        // 创建保存按钮
        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(e -> {
            try {
                // 删除原有联系人
                contactDAO.deleteContact(contact.getName());
                
                // 创建新的联系人对象
                Contact updatedContact;
                if (typeCombo.getSelectedItem().equals("朋友")) {
                    updatedContact = new FriendContact(
                        nameField.getText(),
                        phoneField.getText(),
                        emailField.getText(),
                        extraField.getText()
                    );
                } else {
                    updatedContact = new WorkContact(
                        nameField.getText(),
                        phoneField.getText(),
                        emailField.getText(),
                        extraField.getText()
                    );
                }
                
                // 添加更新后的联系人
                contactDAO.addContact(updatedContact);
                refreshTable();
                dialog.dispose();
            } catch (ContactException ex) {
                JOptionPane.showMessageDialog(dialog, ex.getMessage());
            }
        });

        // 创建取消按钮
        JButton cancelButton = new JButton("取消");
        cancelButton.addActionListener(e -> dialog.dispose());

        // 添加按钮到按钮面板
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);

        // 设置面板边距
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 5, 10));

        // 将组件添加到对话框
        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        
        // 显示对话框
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }

    private void deleteContact() {
        int selectedRow = contactTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要删除的联系人");
            return;
        }

        String name = (String) tableModel.getValueAt(selectedRow, 1);
        try {
            contactDAO.deleteContact(name);
            refreshTable();
        } catch (ContactException e) {
            JOptionPane.showMessageDialog(this, e.getMessage());
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new MainFrame().setVisible(true);
        });
    }
}
